<template>
  <div class="profile-container">
    <h1>个人资料</h1>

    <div class="profile-content">
      <div class="profile-form">
        <h2>基本信息</h2>
        <form @submit.prevent="updateProfile">
          <div class="form-group">
            <label for="avatar">头像</label>
            <div class="avatar-upload">
              <div class="avatar-preview">
                <img :src="profileData.avatar || defaultAvatar" alt="用户头像" />
              </div>
              <button type="button" class="btn btn-sm btn-outline">更换头像</button>
            </div>
          </div>

          <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" v-model="profileData.username" required />
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="realName">真实姓名</label>
              <input type="text" id="realName" v-model="profileData.realName" />
            </div>

            <div class="form-group">
              <label for="phone">手机号码</label>
              <input type="tel" id="phone" v-model="profileData.phone" />
            </div>
          </div>

          <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" id="email" v-model="profileData.email" required />
          </div>

          <div class="form-group">
            <label for="school">学校/单位</label>
            <input type="text" id="school" v-model="profileData.school" />
          </div>

          <div class="form-group">
            <label for="bio">个人简介</label>
            <textarea id="bio" v-model="profileData.bio" rows="4"></textarea>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
              {{ isSubmitting ? '保存中...' : '保存修改' }}
            </button>
          </div>
        </form>
      </div>

      <div class="profile-sidebar">
        <div class="card security-card">
          <h2>账号安全</h2>
          <div class="security-item">
            <div class="security-info">
              <h3>修改密码</h3>
              <p>定期更改密码可以提高账号安全性</p>
            </div>
            <button class="btn btn-sm btn-outline" @click="showPasswordModal = true">修改</button>
          </div>

          <div class="security-item">
            <div class="security-info">
              <h3>绑定手机</h3>
              <p>
                {{
                  profileData.phone ? '已绑定: ' + maskPhone(profileData.phone) : '未绑定手机号码'
                }}
              </p>
            </div>
            <button class="btn btn-sm btn-outline" @click="showPhoneModal = true">
              {{ profileData.phone ? '更换' : '绑定' }}
            </button>
          </div>

          <div class="security-item">
            <div class="security-info">
              <h3>登录设备</h3>
              <p>查看最近登录的设备和位置</p>
            </div>
            <button class="btn btn-sm btn-outline" @click="showDevicesModal = true">查看</button>
          </div>
        </div>

        <div class="card account-card">
          <h2>账号信息</h2>
          <ul class="account-info">
            <li>
              <span class="info-label">账号类型</span>
              <span class="info-value">{{ roleText }}</span>
            </li>
            <li>
              <span class="info-label">注册时间</span>
              <span class="info-value">{{ formatDate(profileData.createdAt) }}</span>
            </li>
            <li>
              <span class="info-label">上次登录</span>
              <span class="info-value">{{ formatDate(profileData.lastLogin) }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div v-if="showPasswordModal" class="modal-overlay" @click="showPasswordModal = false">
      <div class="modal-content" @click.stop>
        <h2>修改密码</h2>
        <form @submit.prevent="changePassword">
          <div class="form-group">
            <label for="currentPassword">当前密码</label>
            <input
              type="password"
              id="currentPassword"
              v-model="passwordForm.currentPassword"
              required
            />
          </div>

          <div class="form-group">
            <label for="newPassword">新密码</label>
            <input type="password" id="newPassword" v-model="passwordForm.newPassword" required />
          </div>

          <div class="form-group">
            <label for="confirmPassword">确认新密码</label>
            <input
              type="password"
              id="confirmPassword"
              v-model="passwordForm.confirmPassword"
              required
            />
          </div>

          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="showPasswordModal = false">
              取消
            </button>
            <button type="submit" class="btn btn-primary">确认修改</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 默认头像
const defaultAvatar = 'https://via.placeholder.com/100'

// 提交状态
const isSubmitting = ref(false)

// 弹窗状态
const showPasswordModal = ref(false)
const showPhoneModal = ref(false)
const showDevicesModal = ref(false)

// 个人资料数据
const profileData = ref({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  school: '',
  bio: '',
  avatar: '',
  role: 'teacher',
  createdAt: new Date(),
  lastLogin: new Date(),
})

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 计算角色文本
const roleText = computed(() => {
  const roleMap: Record<string, string> = {
    teacher: '教师账号',
    student: '学生账号',
    admin: '管理员账号',
  }
  return roleMap[profileData.value.role] || '普通账号'
})

// 加载个人资料
const loadProfile = async () => {
  try {
    // 模拟加载数据
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 实际项目中应从API获取数据
    profileData.value = {
      id: '1',
      username: 'teacher001',
      realName: '张老师',
      phone: '13800138000',
      email: 'teacher@example.com',
      school: '示范中学',
      bio: '初中语文教师，有10年教学经验，喜欢研究语文教学方法和备课技巧。',
      avatar: 'https://via.placeholder.com/100',
      role: 'teacher',
      createdAt: new Date('2022-09-01'),
      lastLogin: new Date('2023-03-20'),
    }
  } catch (error) {
    console.error('加载个人资料失败', error)
  }
}

// 更新个人资料
const updateProfile = async () => {
  try {
    isSubmitting.value = true

    // 模拟提交请求
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 实际项目中应调用API保存
    alert('个人资料已更新')
  } catch (error) {
    console.error('更新个人资料失败', error)
    alert('更新失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      alert('两次输入的密码不一致')
      return
    }

    // 模拟提交请求
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 实际项目中应调用API修改密码
    alert('密码已修改，请重新登录')

    // 清空表单
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    }

    // 关闭弹窗
    showPasswordModal.value = false
  } catch (error) {
    console.error('修改密码失败', error)
    alert('修改失败，请重试')
  }
}

// 手机号码脱敏
const maskPhone = (phone: string) => {
  if (!phone || phone.length < 8) return phone
  return phone.slice(0, 3) + '****' + phone.slice(-4)
}

// 日期格式化
const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

h1 {
  margin-bottom: 24px;
  color: #333;
}

h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
  font-size: 1.5rem;
}

h3 {
  margin: 0 0 5px 0;
  font-size: 1rem;
  color: #333;
}

.profile-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.profile-form,
.card {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

textarea {
  resize: vertical;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #eee;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.profile-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-card,
.account-card {
  height: fit-content;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
}

.security-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.security-info p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 0.9rem;
}

.account-info {
  list-style: none;
  padding: 0;
  margin: 0;
}

.account-info li {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.account-info li:last-child {
  border-bottom: none;
}

.info-label {
  color: #666;
}

.info-value {
  font-weight: 500;
  color: #333;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  border: none;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 0.9rem;
}

.btn-outline {
  background-color: transparent;
  border: 1px solid #4caf50;
  color: #4caf50;
}

.btn-primary {
  background-color: #4caf50;
  color: white;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }

  .form-row {
    grid-template-columns: 1fr;
  }
}
</style>
